/*
 * @Author: czy
 * @Date: 2021-04-26 07:41:28
 * @LastEditTime: 2021-07-12 22:15:17
 */
#include "stdbool.h"
#include "string.h"

#include "sys/container.h"
#include "sys/system.h"
#include "sys/type.h"

#include "../lib/cmd.h"

static Map cmdMap = newMap(command);
/**
 * @description: Add a command to the command list.
 * @param name          Name of the command.
 * @param help_content  Help content of the command
 * @param func          Function.
 */
void addNewCmd(char *name, char *help_content, int (*func)(int argc, char *argv[]))
{
    command cmd;
    strcpy(cmd.name, name);
    strcpy(cmd.help_content, help_content);
    cmd.func = func;
    cmdMap.set(&cmdMap, name, &cmd);
    command *temp = (command *)cmdMap.get(&cmdMap, name);
}

/**
 * @description: Match the input command with the registered command.
 * @param name  Name of command.
 * @param cmd   Matching command.
 * @return true if match, else false.
 */
int match(char *name, command *cmd)
{
    command *temp;
    temp = (command *)cmdMap.get(&cmdMap, name);
    if (temp != NULL)
    {
        memcpy(cmd, temp, sizeof(command));
        return true;
    }
    return false;
}

/**
 * @description: Submit the current instruction to the shell.
 */
void submitCmd(char *str)
{
    int argc;
    char *argv[MAX_ARGC];
    command cmd;
    argc = split(argv, str, " ");
    if (argc == 1 && *argv[0] == '\0')
    {
        return;
    }
    if (match(argv[0], &cmd))
    {
        cmd.func(argc, argv);
    }
    else
    {
        printk("%s: command not found\n", argv[0]);
    }
}

/**
 * @description: Returns a pointer to the command structure.
 * @return Pointer.
 */
void *cmd_pointer(void)
{
    return (void *)(&cmdMap);
}